package cn.lxh.ymcc.listener;

import cn.lxh.ymcc.domain.CourseOrder;
import cn.lxh.ymcc.dto.PayDto;
import cn.lxh.ymcc.service.ICourseOrderService;
import cn.lxh.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-order-producer"  //要和发送事务消息指明的名字一致
)
@Slf4j
public class CourseOrderRocketMqListener  implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;
    /**
     * 执行本地事务
     *   需要在此方法中保存主订单和子订单
     * rocketmq中有大量
     *      - COMMIT,
     *      - ROLLBACK,
     *      - UNKNOWN;
     *
     *
     *
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        //保存本地事务  主订单 + 子订单保存
        log.info("执行本事务");
        if(arg == null){
            return RocketMQLocalTransactionState.ROLLBACK;//参数都没有，直接回滚
        }
        try {
            CourseOrder courseOrder = (CourseOrder) arg;
            courseOrderService.saveOrderAndItems(courseOrder);//保存主订单和子订单
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//执行本地事务失败
        }
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }

    /**
     * 事务消息回查功能
     * 检查本地事务
     *   检查本地的主订单和子订单是否保存成功
     *   -事务消息
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 根据消息体去查询本地事务是否已经执行成功
        // byte[] --> jsonString   -->PayDto 对象
        log.info("检查本地事务状态");
        try {
            byte[] bytOjb = (byte[])message.getPayload();
            String messgeStr = new String(bytOjb, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(messgeStr, PayDto.class);
            /*
                回查这个订单
                    -订单不存在。。回调
                    -订单存在，提交
             */
            CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(payDto.getOrderNo());
            return courseOrder == null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}